package com.wwj.my_ummary.goods.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.my_ummary.goods.entity.Goods;
import com.wwj.my_ummary.goods.entity.Order;
import com.wwj.my_ummary.goods.mapper.GoodsMapper;
import com.wwj.my_ummary.goods.mapper.OrderMapper;
import com.wwj.my_ummary.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-01-14
 */
@Service
@Transactional()
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    private GoodsMapper goodsDao;
    @Autowired
    private OrderMapper orderDao;

    /**
     * 扣减库存
     * @param gid 商品id
     * @param uid 用户id
     * @return SUCCESS 1 FAILURE 0
     */
    @Override
    public int sellGoods(int gid, int uid) {

        /**
         *  获取库存
         */
        Goods goods = goodsDao.getStock(gid);
        if (goods.getStock() > 0) {
            /**
             *   更新库存
             */

            goods.setStock(goods.getStock()+1);



            int update = goodsDao.decreaseStockForVersion(gid, goods.getVersion());
            /**
             * 更新失败，说明其他线程已经修改过数据，本次扣减库存失败，可以重试一定次数或者返回
             */
            if (update == 0) {
                return 0;
            }
            /**
             * 库存扣减成功，生成订单
             */
            Order order = new Order();
            order.setUid(uid);
            order.setGid(gid);
            int result = orderDao.insertOrder(order);
            return result;
        }
        // 失败返回
        return 0;
    }
}
